<?php

namespace app\hotel\controller;

use think\Controller;
// 引入邮箱
use app\common\library\Email;

class Business extends Controller
{
    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->BusinessModel = model('Business.Business');
        $this->SourceModel = model('Business.Source');
        $this->EmsModel = model('Ems');
        $this->RoomModel = model('Hotel.Room');
        $this->CouponReceiveModel = model('Coupon.Receive');
    }

    // 登陆
    public function login()
    {
        if ($this->request->isPost())
        {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            // 数据查询用户信息是否存在
            $Business = $this->BusinessModel->where('mobile', $mobile)->find();

            // 登陆
            if ($Business)
            {
                $password = md5($password . $Business['salt']);

                if ($password != $Business['password'])
                {
                    $this->error('密码错误');
                    exit;
                }

                // 删除不需要的信息
                unset($Business['password']);
                unset($Business['salt']);

                $this->success('登陆成功', '', $Business);
            }
            // 注册
            else
            {
                // 密码盐
                $salt = build_randstr();

                // 密码加密
                $password = md5($password . $salt);

                // 查询某个字段的值
                $sourceid = $this->SourceModel->where('name', 'like', '%酒店预订%')->value('id');

                $data = [
                    'mobile' => $mobile,
                    'nickname' => $mobile,
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0',
                    'sourceid' => $sourceid ?? null,
                    'auth' => '0'
                ];


                $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                if ($result === false)
                {
                    $this->error($this->BusinessModel->getError());
                    exit;
                }
                else
                {
                    // 通过自增ID获取刚注册的客户信息
                    $Business = $this->BusinessModel->find($this->BusinessModel->id);

                    // 删除不需要的信息
                    unset($Business['password']);
                    unset($Business['salt']);

                    $this->success('注册登录成功', '', $Business);
                    exit;
                }
            }
        }
    }

    // 校验
    public function check()
    {
        if ($this->request->isPost())
        {
            $busid = $this->request->param('id', 0, 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');

            $Business = $this->BusinessModel->where(['id' => $busid, 'mobile' => $mobile])->find();

            if (!$Business)
            {
                $this->error('用户不存在');
                exit;
            }

            // 删除不需要的信息
            unset($Business['password']);
            unset($Business['salt']);

            $this->success('登陆成功', '', $Business);
        }
    }

    // 基本资料
    public function profile()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->param();
            $busid = $this->request->param('busid', 0, 'trim');

            $Business = $this->BusinessModel->find($busid);

            if (!$Business)
            {
                $this->error('用户不存在');
                exit;
            }

            $data = [
                'id' => $busid,
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'gender' => $params['gender'],
                'province' => $params['province'],
                'city' => $params['city'],
                'district' => $params['district']
            ];

            // 判断是否修改邮箱
            if (isset($params['email']) && $params['email'] != $Business['email'])
            {
                $data['email'] = $params['email'];
                $data['auth'] = '0';
            }

            // 判断是否修改密码
            if (isset($params['password']) && !empty($params['password']))
            {
                // 密码盐
                $data['salt'] = build_randstr();

                // 密码加密
                $data['password'] = md5($params['password'] . $data['salt']);
            }


            // 判断是否修改头像
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0)
            {
                $res = upload('avatar');

                var_dump($res);

                if ($res['code'] == 0)
                {
                    $this->error($res['msg']);
                    exit;
                }

                $data['avatar'] = $res['data'];
            }

            // 显式指定更新数据操作  需要验证场景
            $result = $this->BusinessModel->validate('common/Business/Business.edit')->isUpdate(true)->save($data);

            if ($result === false)
            {
                if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0)
                {
                    is_file(trim($data['avatar'], '/')) && unlink(trim($data['avatar'], '/'));
                }
                $this->error($this->BusinessModel->getError());
                exit;
            }
            else
            {
                if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0)
                {
                    is_file(trim($Business['avatar'], '/')) && unlink(trim($Business['avatar'], '/'));
                }
                
                $Business = $this->BusinessModel->find($busid);

                // 删除不需要的信息
                unset($Business['password']);
                unset($Business['salt']);

                $this->success('修改资料成功', '', $Business);
                exit;
            }
        }
    }

    // 发送邮件
    public function send()
    {
        if ($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');

            $Business = $this->BusinessModel->find($busid);

            if (!$Business)
            {
                $this->error('用户不存在');
                exit;
            }


            $emsinfo = $this->EmsModel->where('email', $Business['email'])->find();

            if ($emsinfo)
            {
                $this->success('邮件已发送，请注意查收');
                exit;
            }

            // 启动事务
            $this->EmsModel->startTrans();

            // 获取验证码
            $code = build_randstr(4);

            $EmsData = [
                'event' => '酒店预订邮箱认证',
                'email' => $Business['email'],
                'code' => $code
            ];

            $EmsStatus = $this->EmsModel->save($EmsData);

            if ($EmsStatus === false)
            {
                $this->error($this->EmsModel->getError());
                exit;
            }

            // 实例化一个Email对象
            $email = new Email;

            $content = "<h1>酒店预订邮箱验证码: $code</h1>";

            $SendEms = $email->subject('酒店预订邮箱认证')->to($Business['email'])->message($content)->send();

            if ($SendEms === false)
            {
                // 回滚事务
                $this->EmsModel->rollback();
                $this->error($email->getError());
                exit;
            }

            if ($EmsStatus === false || $SendEms === false)
            {
                $this->EmsModel->rollback();
                $this->error('发送邮件失败');
                exit;
            }
            else
            {
                // 提交事务
                $this->EmsModel->commit();
                $this->success('发送邮件成功');
                exit;
            }
        }
    }

    // 邮箱认证
    public function email()
    {
        if ($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $code = $this->request->param('code', '', 'trim');

            $Business = $this->BusinessModel->find($busid);

            if (!$Business)
            {
                $this->error('用户不存在');
                exit;
            }

            $emsinfo = $this->EmsModel->where(['email' => $Business['email'], 'code' => $code])->find();

            if (!$emsinfo)
            {
                $this->error('验证码错误，请重新输入');
                exit;
            }

            // 启动事务
            $this->EmsModel->startTrans();
            $this->BusinessModel->startTrans();

            $EmsStatus = $this->EmsModel->destroy($emsinfo['id']);

            if ($EmsStatus === false)
            {
                $this->error($this->EmsModel->getError());
                exit;
            }

            $BusinessStatus = $this->BusinessModel->where('id', $busid)->update(['auth' => '1']);

            if ($BusinessStatus === false)
            {
                $this->EmsModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            if ($EmsStatus === false || $BusinessStatus === false)
            {
                $this->EmsModel->rollback();
                $this->BusinessModel->rollback();
                $this->error('邮箱认证失败');
                exit;
            }
            else
            {
                $this->EmsModel->commit();
                $this->BusinessModel->commit();
                $this->success('邮箱认证成功');
                exit;
            }
        }
    }
    
    // 关于我们
    public function about()
    {
        if($this->request->isPost())
        {
            $list = $this->RoomModel->order('id desc')->limit(5)->select();

            $info = [
                'hotel_name' => config('site.hotel_name') ?? '',
                'hotel_desc' => config('site.hotel_desc') ?? '',
                'hotel_store' => config('site.hotel_store') ?? '',
                'hotel_details' => config('site.hotel_details') ?? '',
            ];

            $data = [
                'list' => $list,
                'info' => $info
            ];

            $this->success('获取成功', '', $data);
        }
    }
    
    //优惠券
    public function coupon()
    {
        if ($this->request->isPost())
        {
            $page = $this->request->param('page', 1, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');
            $status = $this->request->param('status', 'all', 'trim');

            $Business = $this->BusinessModel->find($busid);

            if (!$Business)
            {
                $this->error('用户不存在');
                exit;
            }

            $where = ['busid' => $busid];

            if($status != 'all')
            {
                $where['receive.status'] = $status;
            }

            $list = $this->CouponReceiveModel->with('coupon')->where($where)->order('createtime desc')->page("$page,10")->select();

            if ($list)
            {
                $this->success('', '', $list);
                exit;
            }
            else
            {
                $this->error('暂无数据');
                exit;
            }
        }
    }
}
